import { useProvidersOrderedByOrder } from "@renderer/queries";
import { useActiveProviderId } from "@renderer/queries/hooks/use-ui";
import logger from "@shared/logger/renderer-logger";
import type { Provider } from "@shared/triplit/types";
import { useCallback, useEffect, useMemo, useRef } from "react";

const { uiService } = window.service;

export function useActiveProvider() {
  const hasSetDefault = useRef(false);

  // Subscribe to UI state changes
  const { data: activeProviderId } = useActiveProviderId();

  // Subscribe to providers changes
  const { data: providers } = useProvidersOrderedByOrder();

  // Derive selected provider from activeProviderId and providers
  const selectedProvider = useMemo(() => {
    if (!providers || providers.length === 0) {
      return null;
    }

    if (activeProviderId) {
      return providers.find((p) => p.id === activeProviderId) || null;
    }

    return providers[0] || null;
  }, [activeProviderId, providers]);

  // Set default provider when needed
  useEffect(() => {
    if (!providers || providers.length === 0) {
      hasSetDefault.current = false;
      return;
    }

    // Only set default provider once to avoid infinite loop
    if (!activeProviderId && !hasSetDefault.current && providers[0]) {
      hasSetDefault.current = true;
      uiService.updateActiveProviderId(providers[0].id);
    }
  }, [activeProviderId, providers]);

  const setSelectedProvider = useCallback(async (provider: Provider | null) => {
    logger.debug("useActiveProvider: Setting selected provider", {
      providerName: provider?.name || "none",
      providerId: provider?.id || "",
    });
    hasSetDefault.current = true; // Mark as manually set
    await uiService.updateActiveProviderId(provider?.id || "");
  }, []);

  return {
    selectedProvider,
    setSelectedProvider,
  };
}
